package com.example.util;




import java.util.List;


public class TotalBasedRoundRobinAllocator<T> {

    private List<T> dataNodes;

    /**
     * 根据用户总数进行轮询分配
     * @param totalUsers 当前用户总数
     * @return 分配的数据节点
     */
    public <T> T allocateNodeByTotal(Integer totalUsers) {
        if(totalUsers == null || totalUsers == 0) {
            return (T) this.dataNodes.get(0);
        }
        // 核心逻辑：使用总数对节点数量取模
        int nodeIndex = (int) (totalUsers % this.dataNodes.size());
        T node = (T) this.dataNodes.get(nodeIndex);
        return node;
    }


    public <T> T allocateNodeByHash(String hashSerial) {
        int hash = hashSerial.hashCode();
        int tableIndex = Math.abs(hash) % this.dataNodes.size();
        T node = (T) this.dataNodes.get(tableIndex);
        return node;
    }


    public TotalBasedRoundRobinAllocator(List<T> dataNodes) {
        this.dataNodes = dataNodes;
    }
}
